import uuid
from google.appengine.ext  import db
from ironcap.models.counters import Counter

class Votes(db.Model):
	""" vote system """ 
	reference     = db.ReferenceProperty(db.Model)
	counter_up    = db.ReferenceProperty(Counter, collection_name='counter_up')
	counter_down  = db.ReferenceProperty(Counter, collection_name='counter_down')
	
	@classmethod
	def create(cls, **kwds):
		ret = cls(key_name=str(uuid.uuid4()))
		ret.put()
		ret.counter_up   = Counter.create(reference=ret)
		ret.counter_down = Counter.create(reference=ret)
		
		# apply keywords
		for k,v in kwds.iteritems():
			setattr(ret, k, v)			
		
		ret.put()
		return ret
	
	def vote_up(self):
		self.counter_up.increment(1)
	
	def vote_down(self):
		self.counter_down.increment(1)
	
	def delete(self):
		try:
			if self.counter_up:
				self.counter_up.delete()
		except:
			pass
		try:
			if self.counter_down:
				self.counter_down.delete()
		except:
			pass
		db.delete(self.key())
